package com.dongdong.lication;

import com.dongdong.job.JobDemo;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@Component
public class QuartzListener implements ApplicationListener<ContextClosedEvent> {
    @Autowired
    private Scheduler scheduler;
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        try {
            //这是好组名
            TriggerKey triggerKey = TriggerKey.triggerKey("trigger1", "group1");
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (trigger == null){   //灭有触发器
                trigger = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey)
                        //3秒执行一次
                        .withSchedule(CronScheduleBuilder.cronSchedule("*/3 * * * * ?"))
                        .build();

                JobDetail jobDetail = JobBuilder.newJob(JobDemo.class)
                        .withIdentity("job1", "group2")
                        .build();
                scheduler.scheduleJob(jobDetail,trigger);
                //开始调度
                scheduler.start();
            }
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }
}